package com.qxjc.manage.web.park;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.qxjc.manage.entity.ParkInfoVO;
import com.qxjc.manage.pojo.Dept;
import com.qxjc.manage.pojo.ParkApplyImage;
import com.qxjc.manage.pojo.ParkApplyInfo;
import com.qxjc.manage.pojo.User;
import com.qxjc.manage.service.DeptService;
import com.qxjc.manage.service.ParkService;
import com.qxjc.manage.utils.Result;
import com.qxjc.manage.utils.keyUtil;
import com.sun.org.apache.regexp.internal.recompile;

import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/park")
@Slf4j
public class ParkController {

	@Autowired
	private ParkService parkService;
	@Autowired
	private DeptService deptService;
	

	@RequestMapping("step")
	public ModelAndView toStep() {
		ModelAndView mav = new ModelAndView("/park/apply/steps");
		return mav;
	}

	@RequestMapping("toBasicImage")
	public ModelAndView toBasicinfo() {
		ModelAndView mav = new ModelAndView("/park/apply/upload-image");
		return mav;
	}

	
	@RequestMapping("toBasicInfo")
	public ModelAndView toBasicInfo(@ModelAttribute("imageId") Integer imageId, Map<String, Object> map) {
		ModelAndView mav = new ModelAndView("park/apply/upload-basic");
		List<Dept> deptList = deptService.DeptList();
		mav.addObject("imageId", imageId);
		mav.addObject("deptList", deptList);
		return mav;
	}
	
	
	@PostMapping("basicImage")
	public ModelAndView insertBasicImage(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		ParkApplyImage parkApplyImage = new ParkApplyImage();
	//	parkApplyImage.setId(keyUtil.genUniqueKeyByUid());
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			try {
//				if (file.isEmpty()) {
//					File f = new File("D://test//images//demo.png");
//				    FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(f.toPath()), false, f.getName(), (int) f.length(), f.getParentFile());
//				    InputStream input = new FileInputStream(f); OutputStream os = fileItem.getOutputStream();
//				        IOUtils.copy(input, os);
//				        file = new CommonsMultipartFile(fileItem);
//				}
				if (!file.isEmpty()) {
					byte[] bytes = file.getBytes();
					// 获取文件名
					String fileName = file.getOriginalFilename();
					log.info("上传的文件名为：" + fileName);
					// 获取文件的后缀名
					String suffixName = fileName.substring(fileName.lastIndexOf("."));
					log.info("上传的后缀名为：" + suffixName);
					// 文件上传后的路径
					String filePath = "D://test//";
					// 解决中文问题，liunx下中文路径，图片显示问题
					// fileName = UUID.randomUUID() + suffixName;
					File dest = new File(filePath + UUID.randomUUID() + suffixName);
					// 检测是否存在目录
					if (!dest.getParentFile().exists()) {
						dest.getParentFile().mkdirs();
					}

					file.transferTo(dest);
					String fileToBase64 = Base64.getEncoder().encodeToString(bytes);
					switch (i) {
					case 0:
						parkApplyImage.setYyzz(fileToBase64);
						break;
					case 1:
						parkApplyImage.setFrsfzj(fileToBase64);
						break;
					case 2:
						parkApplyImage.setJbrsfzj(fileToBase64);
						break;
					case 3:
						parkApplyImage.setTdz(fileToBase64);
						break;
					case 4:
						parkApplyImage.setPmt(fileToBase64);
						break;
					case 5:
						parkApplyImage.setSbqd(fileToBase64);
						break;
					case 6:
						parkApplyImage.setSfbz(fileToBase64);
						break;
					case 7:
						parkApplyImage.setTfzd(fileToBase64);
						break;
					case 8:
						parkApplyImage.setAqzd(fileToBase64);
						break;
					case 9:
						parkApplyImage.setFxzd(fileToBase64);
						break;
					case 10:
						parkApplyImage.setXfzd(fileToBase64);
						break;
					case 11:
						parkApplyImage.setTdzlht1(fileToBase64);
						break;
					case 12:
						parkApplyImage.setTdzlht2(fileToBase64);
						break;
					case 13:
						parkApplyImage.setTdzlht3(fileToBase64);
						break;
					}
					
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		parkService.insertParkApplyImage(parkApplyImage);
		redirectAttributes.addFlashAttribute("imageId", parkApplyImage.getId());
		return new ModelAndView("redirect:/park/toBasicInfo");
	}
	
	
	@PostMapping("/basicInfo")
	public ModelAndView insertBasicInfo(ParkApplyInfo applyInfo) {
		ModelAndView mav = new ModelAndView("redirect:/park/u");
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		Integer userId = existUser.getId();
		applyInfo.setId(keyUtil.genUniqueKeyAll());
		applyInfo.setUserId(userId.toString());
		parkService.insertParkApplyInfo(applyInfo);
		return mav;
	}
	
	
	@GetMapping("/u")
	public ModelAndView selectBasicInfoList() {
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		Integer userId = existUser.getId();
		ModelAndView mav = new ModelAndView("park/apply/basic-list");
		List<ParkApplyInfo> applyInfoList = parkService.selectParkApplyInfoByUserId(userId.toString());
		log.debug("停车场基本信息查询=applyInfoList:" + applyInfoList.toString());
		mav.addObject("applyInfoList", applyInfoList);
		return mav;
	}
	
	
	@GetMapping("/basic/{id}")
	public ModelAndView selectBasicInfoById(@PathVariable String id) {
		ModelAndView mav = new ModelAndView("park/apply/basic-info");
		ParkApplyInfo applyInfo = parkService.selectParkApplyInfoById(id);
		ParkApplyImage applyImage = parkService.selectParkApplyImageById(applyInfo.getApplyImgId());
		log.debug("停车场基本信息查询=applyInfo:" + applyInfo.toString());
		log.debug("停车场图像信息查询=applyImage:" + applyImage);
		mav.addObject("applyInfo", applyInfo);
		mav.addObject("applyImage", applyImage);
		return mav;
	}
	
	@GetMapping("/invalid/{id}")
	@ResponseBody
	public String deleteBasicInfoById(@PathVariable String id) {
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		Integer userId = existUser.getId();
		if (id!=null) {
			ParkApplyInfo  applyInfo = parkService.selectParkApplyInfoById(id);
			if (StringUtils.isEmpty(applyInfo)) {
				return "撤销失败，申请不存在";
			}if (!applyInfo.getUserId().equals(userId.toString())) {
				return "撤销失败，操作人和申请人不一致";
			}
			applyInfo.setState(3);
			parkService.updateParkApplyInfo(applyInfo);
			return "撤销成功";
		}
		return "撤销失败，参数为空";
	}
	
	@GetMapping("/modify/{id}")
	public ModelAndView modifyBasicInfoById(@PathVariable String id) {
		ModelAndView mav = new ModelAndView("park/apply/modify");
		ParkApplyInfo applyInfo = parkService.selectParkApplyInfoById(id);
		if (applyInfo != null) {
			ParkApplyImage applyImage = parkService.selectParkApplyImageById(applyInfo.getApplyImgId());
			List<Dept> deptList = deptService.DeptList();
			mav.addObject("deptList", deptList);
			mav.addObject("applyinfo",applyInfo);
			mav.addObject("applyimage",applyImage);
		}
		return mav;
	}
	
	@PostMapping("/update")
	@Transactional
	public ModelAndView updateBasicInfoById(ParkInfoVO park) throws Exception {
		
		ModelAndView mav = new ModelAndView("redirect:/park/u");
		ParkApplyInfo info = parkService.selectParkApplyInfoById(park.getInfoId());
		ParkApplyImage image = parkService.selectParkApplyImageById(info.getApplyImgId());
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		Integer userId = existUser.getId();
		
		if (info == null) {
			mav = new ModelAndView("/error");
			Result<String> result = new Result<String>(
					"出错了", "1003", "修改出错，申请不存在");
			mav.addObject("result", result);
		}
		if (!userId.toString().equals(info.getUserId())) {
			mav = new ModelAndView("/error");
			Result<String> result = new Result<String>(
					"出错了", "1002", "修改出错，您无权操作该");
			mav.addObject("result", result);
		}
		
		info.setAddress(park.getAddress());
		info.setApplyType(park.getApplyType());
		info.setBoss(park.getBoss());
		info.setBossPhone(park.getBossPhone());
		info.setDeptId(park.getDeptId());
		info.setHeader(park.getHeader());
		info.setHeaderPhone(park.getHeaderPhone());
		info.setGround(park.getGround());
		info.setMachine(park.getMachine());
		info.setName(park.getName());
		info.setParkArea(park.getParkArea());
		info.setParkSum(park.getParkSum());
		info.setRemark(park.getRemark());
		info.setType(park.getType());
		info.setUnderground(park.getUnderground());
		info.setYard(park.getYard());
		
		
			if (!park.getYyzz().getOriginalFilename().equals("")) {
				image.setYyzz(fileToBase64(park.getYyzz()));
			}
			if (!park.getAqzd().getOriginalFilename().equals("")) {
				image.setAqzd(fileToBase64(park.getAqzd()));
			}
			if (!park.getFrsfzj().getOriginalFilename().equals("")) {
				image.setFrsfzj(fileToBase64(park.getFrsfzj()));
			}
			if (!park.getFxzd().getOriginalFilename().equals("")) {
				image.setFxzd(fileToBase64(park.getFxzd()));
			}
			if (!park.getJbrsfzj().getOriginalFilename().equals("")) {
				image.setJbrsfzj(fileToBase64(park.getJbrsfzj()));
			}
			if (!park.getPmt().getOriginalFilename().equals("")) {
				image.setPmt(fileToBase64(park.getPmt()));
			}
			if (!park.getSbqd().getOriginalFilename().equals("")) {
				image.setSbqd(fileToBase64(park.getSbqd()));
			}
			if (!park.getSfbz().getOriginalFilename().equals("")) {
				image.setSfbz(fileToBase64(park.getSfbz()));
			}
			if (!park.getSwdjz().getOriginalFilename().equals("")) {
				image.setSwdjz(fileToBase64(park.getSwdjz()));
			}
			if (!park.getTdz().getOriginalFilename().equals("")) {
				image.setTdz(fileToBase64(park.getTdz()));
			}
			if (!park.getTdz().getOriginalFilename().equals("")) {
				image.setTdz(fileToBase64(park.getTdz()));
			}
			if (!park.getTdzlht1().getOriginalFilename().equals("")) {
				image.setTdzlht1(fileToBase64(park.getTdzlht1()));
			}
			if (!park.getTdzlht2().getOriginalFilename().equals("")) {
				image.setTdzlht2(fileToBase64(park.getTdzlht2()));
			}
			if (!park.getTdzlht3().getOriginalFilename().equals("")) {
				image.setTdzlht3(fileToBase64(park.getTdzlht3()));
			}
			if (!park.getTfzd().getOriginalFilename().equals("")) {
				image.setTfzd(fileToBase64(park.getTfzd()));
			}
			if (!park.getXfzd().getOriginalFilename().equals("")) {
				image.setXfzd(fileToBase64(park.getXfzd()));
			}
			if (!park.getZhpt().getOriginalFilename().equals("")) {
				image.setZhpt(fileToBase64(park.getZhpt()));
			}
		
			parkService.updateParkApplyInfo(info);
			parkService.updateParkApplyImage(image);
		
		return mav;
	}
	
	
	
	public String fileToBase64(MultipartFile file) throws Exception {
		String fileToBase64 = null;
		if (!file.isEmpty()) {
			byte[] bytes = file.getBytes();
			// 获取文件名
			String fileName = file.getOriginalFilename();
			log.info("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			log.info("上传的后缀名为：" + suffixName);
			// 文件上传后的路径
			String filePath = "D://test//";
			// 解决中文问题，liunx下中文路径，图片显示问题
			// fileName = UUID.randomUUID() + suffixName;
			File dest = new File(filePath + UUID.randomUUID() + suffixName);
			// 检测是否存在目录
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}

			file.transferTo(dest);
			fileToBase64 = Base64.getEncoder().encodeToString(bytes);
		}
		return fileToBase64;
	}
}
